<template>
    <div class="dai">
        <div class="cont">
            <div class="abb">
                <h1>仓库信息</h1>
                <div class="nmb">
                    <div class="nmbs">
                        输入调拨订单ID:<el-input v-model="filters.id" clearable @change="loadwarehouses"></el-input>
                    </div>
                    <div class="nmbs">
                        选择调拨单号:<el-input v-model="filters.transfercode" clearable @change="loadwarehouses"></el-input>

                    </div>
                    <div class="nmbs">
                        调拨类型:<el-input v-model="filters.transfertype" clearable @change="loadwarehouses"></el-input>
                        <el-button @click="resfrom">重置</el-button>
                    </div>
                </div>
            </div>
            <div class="a">
                <el-col>
                    <el-button :icon="CirclePlus" @click="insert">添加</el-button>
                </el-col>
            </div>
            <div>
                <el-table :data="tabos" border>
                    <el-table-column label="调拨订单ID" prop="id">
                        <template #default="scope">
                            <span class="clickable-id" @click="openDetails(scope.row.id)">
                                {{ scope.row.id }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="调拨单号" prop="transfercode"></el-table-column>
                    <el-table-column label="调拨单名称" prop="transfername"></el-table-column>
                    <el-table-column label="调出仓库ID" prop="fromWarehouseid"></el-table-column>
                    <el-table-column label="调入仓库ID" prop="toWarehouseid"></el-table-column>
                    <el-table-column label="调拨类型" prop="transfertype"></el-table-column>
                    <el-table-column label="调拨时间" prop="transfertime"></el-table-column>
                    <el-table-column label="状态" prop="status">
                        <template #default="scope">
                            <span v-if="scope.row.status === 1" style="color: #faad14;">正在审核</span>
                            <span v-if="scope.row.status === 2" style="color: #52c41a;">已审核</span>
                            <span v-else>未知状态</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建者" prop="createBy"></el-table-column>
                    <el-table-column label="创建时间" prop="updateTime"></el-table-column>
                    <el-table-column label="更新时间" prop="updateTime"></el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <div class="caozuo">
                                <el-button type="danger" @click="shanchu(scope.row.id)">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>

                </el-table>
            </div>
        </div>
    </div>

    <el-dialog v-if="insertVisible" v-model="insertVisible">
        <router-view @closeDialog="closeDialog">
        </router-view>
    </el-dialog>
    <el-dialog v-if="detailVisible" v-model="detailVisible" title="调拨明细表" :width="auth">
        <router-view :transfer-id="selectedTransferId" @closeDialog="detailVisible = false">
        </router-view>
    </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import request from '@/api/request';
import { useRouter } from "vue-router";
import { CirclePlus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { auth } from '@/directives/auth';

const insertVisible = ref(false)
const detailVisible = ref(false)
const selectedTransferId = ref('')
const router = useRouter();

const checkDetailVisible = ref(false);
const transferDetails = ref([]);
const selectedTfDetails = ref([]);

const submitToTransaction = (row) => {
    if (row.status === 1) {
        ElMessage.warning("当前调拨单正在审核，无法提交流水");
        return;
    }
    if (row.status !== 2) {
        ElMessage.error("当前调拨单状态异常（非已审核），无法提交流水");
        return;
    }
    localStorage.setItem('transferMain', JSON.stringify(row));
    loadDetailsByTransferCode(row.transfercode).then(details => {
        if (details.length === 0) {
            ElMessage.error("该调拨单无对应明细，无法提交流水");
            return;
        }
        transferDetails.value = details;
        checkDetailVisible.value = true;
    });
};
const loadDetailsByTransferCode = async (transferCode) => {
    console.log(transferCode);
    
    try {
        const res = await request({
            method: "get",
            url: "inventory_ssss/trees",
            params: { transferId: transferCode }
        });
        if (res.data?.data) {
            return res.data.data.map(item => ({
                id: item.detailId,
                transferid: item.transferId,
                materialid: item.materialId,
                batchno: item.batchNo,
                shippedquantity: item.shippedQuantity,
                receivedquantity: item.receivedQuantity,
                createtime: new Date(item.createTime).toLocaleDateString()
            }));
        }
        return [];
    } catch (err) {
        ElMessage.error("加载明细异常：" + err.message);
        return [];
    }
};
const handleSelectionChange = (selectioin) => {
    selectedTfDetails.value = selectioin;
};
const confirmDetails = () => {
    if (selectedDetails.value.length === 0) {
        ElMessage.warning("请至少勾选一条明细");
        return;
    }
    localStorage.setItem('selectedDetails', JSON.stringify(selectedTfDetails.value));
    checkDetailVisible.value = false;
    router.push("/warehouse/outbound/insert")
};

const openDetails = (transferId) => {
    selectedTransferId.value = transferId;
    detailVisible.value = true;
    router.push("/warehouse/diaobomingxi/index");
};
const insert = () => {
    insertVisible.value = true;
    router.push("/warehouse/diaobo/insert");
};

const filters = ref({ id: '', transfercode: '', transfertype: '' });
const warehoseList = ref([]);
const loadwarehouses = () => {
    request({
        method: "get",
        url: "inventory_ssss/trees"
    }).then(res => {
        console.log(res.data);
        if (res.data) {
            warehoseList.value = res.data.data.map(item => ({
                id: item.transferId,
                transfercode: item.transferCode,
                transfername: item.transferName,
                fromWarehouseid: item.fromWarehouseId,
                toWarehouseid: item.toWarehouseId,
                transfertype: item.transferType,
                transfertime: new Date(item.transferTime).toLocaleDateString(),
                status: item.status,
                createBy: item.createBy,
                createTime: new Date(item.createTime).toLocaleDateString(),
                updateTime: new Date(item.updateTime).toLocaleDateString()
            }));
        } else {
            console.error("查询失败:", res.message);
            ElMessage.error("查询失败:", +res.message)
        }
    }).catch(err => {
        console.error("请求异常:", err);
        ElMessage.error("加载失败:", err.message)
    });
};
onMounted(loadwarehouses);
const tabos = computed(() => {
    return warehoseList.value.filter(item => {
        const matchId = filters.value.id ? item.id.includes(filters.value.id) : true;
        const matchtransfercode = filters.value.transfercode ? item.transfercode === filters.value.transfercode : true;
        const matchtransfertype = filters.value.transfertype ? item.transfertype === filters.value.transfertype : true;
        return matchId && matchtransfercode && matchtransfertype;
    });
});

const resfrom = () => {
    filters.value = { id: "", transfercode: "", transfertype: "" }
    loadwarehouses();
};

const shanchu = (id) => {
    console.log("要删除的仓库id", id)
    ElMessageBox.confirm("确定删除该仓库", {
        title: '删除确定',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
    })
        .then(() => {
            request({
                method: "delete",
                url: `/inventory_ssss/${id}`,
            })
                .then(res => {
                    if (res.data.success) {
                        ElMessage.success("删除成功");
                        loadwarehouses();
                    } else {
                        console.error('删除失败:', res.message)
                        ElMessage.error(`删除失败:${res.message}`);
                    }
                })
                .catch(err => {
                    console.error('删除异常:', err);
                    ElMessage.error(`删除失败:${err.message || '网络异常'}`)
                })
        })
        .catch(() => {
            ElMessage.info("已取消")
        });
};
const closeDialog = () => {
    insertVisible.value = false;
};
</script>

<style scoped>
.nmb {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    gap: 20px;
    padding: 10px 0;
}

.nmbs {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 280px;
    gap: 10px
}

.nmb span {
    width: 100px;
    text-align: right;
}

.filter-input {
    flex: 1;
    min-width: 180px;
}


.reset-btn {
    margin-left: 10px;
    white-space: nowrap;
}

.a {
    margin-bottom: 20px;
}

.clickable-id {
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
}

.clickable-id:hover {
    color: #66b1ff;
}
</style>
